package com.example.demo.information.controller;

import com.example.demo.account.entity.SysUser;
import com.example.demo.account.entity.SysUserRole;
import com.example.demo.account.service.UserRoleService;
import com.example.demo.account.service.UserService;
import com.example.demo.common.utils.Constant;
import com.example.demo.information.entity.Bjxx;
import com.example.demo.information.entity.School;
import com.example.demo.information.entity.Student;
import com.example.demo.information.entity.info.AdminInfo;
import com.example.demo.information.entity.info.BjxxInfo;
import com.example.demo.information.service.BjxxService;
import com.example.demo.information.service.SchoolService;
import com.example.demo.information.service.StudentService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author littlecar
 * @date 2020/3/23 15:09
 */
@Controller
public class BjxxController {
    @Autowired
    private BjxxService bjxxService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private StudentService studentService;

    @RequestMapping("/toBjxx")
    public String toBjxx(ModelMap map) {
        List<School> list = schoolService.findAll();
        map.addAttribute("xxList", list);
        return "information/bjxx/bjxxList";
    }

    @RequestMapping("/bjxxList")
    @ResponseBody
    public Map<String, Object> bjxxList(String name,Integer page,Integer limit,String xxxx_id) {
        Map<String, Object> map = Maps.newLinkedHashMap();
        int pages = (page - 1) * limit;
        List<BjxxInfo> bjxxInfoList = Lists.newArrayList();
        List<Bjxx> pageBjxxList = Lists.newArrayList();
        List<Bjxx> allBjxxList = Lists.newArrayList();
        if (StringUtils.isNotEmpty(name)) {
            name = "%" + name + "%";
            allBjxxList=bjxxService.findByNameLike(name);
            pageBjxxList = bjxxService.findPageByNameLike(name, pages, limit);
        }else{
            allBjxxList = bjxxService.findAll();
            pageBjxxList = bjxxService.findPageAll(pages, limit);
        }
        for (Bjxx bjxx :
                pageBjxxList) {
            if (StringUtils.isNotEmpty(xxxx_id)) {
                if (bjxx.getSchool().getId().intValue()==Long.valueOf(xxxx_id).intValue()) {
                    bjxxInfoList.add(new BjxxInfo(bjxx));
                }
            }else{
                bjxxInfoList.add(new BjxxInfo(bjxx));
            }
        }
        map.put("data", bjxxInfoList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", allBjxxList.size());
        return map;
    }
    @RequestMapping("/toBjxxAdd")
    public String toBjxxAdd(ModelMap map) {
        List<School> list = schoolService.findAll();
        map.addAttribute("xxList", list);
        Map<Integer, String> result = new LinkedHashMap<>();
        Constant.njmMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        map.addAttribute("njMap", result);
        return "information/bjxx/bjxxAdd";
    }
    @RequestMapping("/toSelectBzr")
    public String toSelectBzr(@RequestParam("bzr_id") String bzr_id,Long xxxx_id, ModelMap map ) {
        map.put("bzr_id", bzr_id);
        map.put("xxxx_id", xxxx_id);
        return "information/bjxx/selectBzr";
    }

    @RequestMapping("/bzrList")
    @ResponseBody
    public Map<String, Object> bzrList(String bzr_name,Long xxxx_id, int page ,int limit) {
        Map<String, Object> map = Maps.newLinkedHashMap();
        int pages = (page-1)*limit;
        List<AdminInfo> adminInfoList= Lists.newArrayList();
        List<SysUser> adminList = Lists.newArrayList();
        List<SysUser> allAdminList = Lists.newArrayList();
        if (StringUtils.isNotEmpty(bzr_name)) {
            bzr_name = "%" + bzr_name + "%";
            allAdminList = userService.findPageBzrByNameLike(bzr_name, xxxx_id, pages, limit);
            adminList = userService.findBzrByNameLike(bzr_name, xxxx_id);
        }else{
            allAdminList = userService.findPageAllBzr(xxxx_id, pages, limit);
            adminList = userService.findAllBzr(xxxx_id);
        }
        for (SysUser user :
                allAdminList) {
            adminInfoList.add(new AdminInfo(user));
        }
        map.put("data", adminInfoList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", adminList.size());
        return map;
    }

    @RequestMapping("/checkBjNameUnique")
    @ResponseBody
    public String checkBjNameUnique(String name,String id) {
        List<Bjxx> bjxxLsit = null;
        if (StringUtils.equals("undefined", id) || StringUtils.isEmpty(id) || StringUtils.isBlank(id)) {
            bjxxLsit = bjxxService.findByName(name);
        } else {
            Bjxx bjxx = bjxxService.findById(Long.valueOf(id));
            if (bjxx.getName().equals(name)) {
                return "false";
            } else {
                bjxxLsit = bjxxService.findByName(name);
            }
        }
        if (null != bjxxLsit && bjxxLsit.size() > 0) {
            return "true";
        }
        return "false";
    }

    @RequestMapping("/checkBjbhUnique")
    @ResponseBody
    public String checkBjbhUnique(String bjbh,String id) {
        if(StringUtils.equals("undefined", bjbh) || StringUtils.isEmpty(bjbh) || StringUtils.isBlank(bjbh)){
            return "false";
        }
        List<Bjxx> bjxxLsit = null;
        if (StringUtils.equals("undefined", id) || StringUtils.isEmpty(id) || StringUtils.isBlank(id)) {
            bjxxLsit = bjxxService.findByBjbh(bjbh);
        } else {
            Bjxx bjxx = bjxxService.findById(Long.valueOf(id));
            if (bjxx.getBjbh().equals(bjbh)) {
                return "false";
            } else {
                bjxxLsit = bjxxService.findByBjbh(bjbh);
            }
        }
        if (null != bjxxLsit && bjxxLsit.size() > 0) {
            return "true";
        }
        return "false";
    }

    @RequestMapping("/bjxxAdd")
    @ResponseBody
    public String bjxxAdd(Bjxx bjxx,Long xxxx_id) {
        try {
            Long id = bjxx.getId();
            if (null == id) {//新增
                bjxx.setRs(0);
                School school = schoolService.findById(xxxx_id);
                bjxx.setSchool(school);
                bjxxService.save(bjxx);
                SysUserRole userRole = userRoleService.findByUserIdAndRoleIdAndSchoolId(bjxx.getBzr_id(), Constant.TEACHER_ID, school.getId());
                if (null == userRole) {
                    SysUserRole userRole1 = userRoleService.findOneByUserIdAndRoleId(bjxx.getBzr_id(), Constant.TEACHER_ID);
                    if (null == userRole1) {
                        userRole1 = new SysUserRole();
                        userRole1.setSchool_id(school.getId());
                        userRole1.setRole_id(Constant.TEACHER_ID);
                        userRole1.setUser_id(bjxx.getBzr_id());
                    }else{
                        userRole1.setSchool_id(school.getId());
                    }
                    userRoleService.save(userRole1);
                }
            }else{//编辑
                Bjxx bjxx1 = bjxxService.findById(id);
                School old_school = bjxx1.getSchool();
                Long old_bzrId = bjxx1.getBzr_id();
                bjxx1.setName(bjxx.getName());
                bjxx1.setShort_name(bjxx.getShort_name());
                bjxx1.setBjbh(bjxx.getBjbh());
                bjxx1.setNjm(bjxx.getNjm());
                bjxx1.setBzr(bjxx.getBzr());
                bjxx1.setBzr_id(bjxx.getBzr_id());
                bjxx1.setSchool(schoolService.findById(xxxx_id));
                //班主任操作
                SysUserRole userRole = userRoleService.findByUserIdAndRoleIdAndSchoolId(bjxx.getBzr_id(), Constant.TEACHER_ID, xxxx_id);
                if (null == userRole) {
                    SysUserRole userRole1 = userRoleService.findOneByUserIdAndRoleId(bjxx.getBzr_id(), Constant.TEACHER_ID);
                    if (null == userRole1) {
                        userRole1 = new SysUserRole();
                        userRole1.setSchool_id(xxxx_id);
                        userRole1.setRole_id(Constant.TEACHER_ID);
                        userRole1.setUser_id(bjxx.getBzr_id());
                    }else{
                        userRole1.setSchool_id(xxxx_id);
                    }
                    userRoleService.save(userRole1);
                }
                //判断原来的班主任是否还在原来的学校中当班主任，
                // 如果没有则将userRole(user_id=old_bzrId,   role_id=6,  school_id=old_school.getId())的school_id改为null
                List<Bjxx> bjxxList=bjxxService.findBySchoolIdAndBzrId(old_school.getId(),old_bzrId);
                if (null == bjxxList || bjxxList.size() <= 0) {
                    SysUserRole userRole1 = userRoleService.findByUserIdAndRoleIdAndSchoolId(old_bzrId, Constant.TEACHER_ID, old_school.getId());
                    if (null != userRole1) {
                        userRole1.setSchool_id(null);
                        userRoleService.save(userRole1);
                    }
                }
                bjxxService.save(bjxx1);
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/bjxxDel")
    @ResponseBody
    public String bjxxDel(String id) {
        try {
            if (StringUtils.isNotEmpty(id)) {
                String[] ids = id.split(",");
                for (String bjId :
                        ids) {
                    List<Student> studentList = studentService.findByBjId(bjId);
                    if (studentList != null && studentList.size() > 0) {
                        return "isExistStu";
                    }
                    bjxxService.deleteById(Long.valueOf(bjId));
                }
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/toBjxxModify")
    public String toBjxxModify(Long id,ModelMap map) {
        Bjxx bjxx = bjxxService.findById(id);
        map.addAttribute("bjxx", bjxx);
        List<School> list = schoolService.findAll();
        map.addAttribute("xxList", list);
        Map<Integer, String> result = new LinkedHashMap<>();
        Constant.njmMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
        map.addAttribute("njMap", result);
        return "information/bjxx/bjxxModify";
    }
}
